package cn.zn.modules.zzsys.his.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.zn.modules.zzsys.his.entity.BasisDept;
import cn.zn.modules.zzsys.his.entity.QBasisDept;
import cn.zn.modules.zzsys.his.repository.BasisDeptRepository;
import cn.zn.modules.zzsys.his.service.HisBasisDeptService;
import com.google.common.collect.Maps;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HisBasisDeptServiceImpl implements HisBasisDeptService {

    @Autowired
    private BasisDeptRepository basisDeptRepository;

    @Override
    public List<Tree<String>> deptTree(Integer ap, String userId) {
        Assert.notNull(ap, "ap 不能为空");
        QBasisDept qBasicDept = QBasisDept.basisDept;
        Predicate predicate = qBasicDept.isNotNull().or(qBasicDept.isNull());
        if (ap != null) {
            predicate = ExpressionUtils.and(predicate, qBasicDept.ap.eq(ap));
        }
        Iterator<BasisDept> basicDeptIterator = basisDeptRepository.findAll(predicate).iterator();
        List<TreeNode<String>> nodeList = CollUtil.newArrayList();
        while (basicDeptIterator.hasNext()) {
            BasisDept basisDept = basicDeptIterator.next();
            Map<String, Object> extra = Maps.newHashMap();
            extra.put("code", basisDept.getCode());
            TreeNode<String> treeNode = new TreeNode<>(basisDept.getDeptId(), basisDept.getPid() == null ? "0" : basisDept.getPid(), basisDept.getName(), basisDept.getSortNum());
            treeNode.setExtra(extra);
            nodeList.add(treeNode);
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setNameKey("text");
        return TreeUtil.build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    tree.putExtra("code", treeNode.getExtra().get("code"));
                });
    }
}
